<template>
    <div class="common-layout">
        <el-button type="primary" plain class="start-stock" @click="this.training = true"
            v-if="!this.training">开始模拟训练</el-button>
        <el-container>
            <el-aside :span="10" class="font-text">
                <h3 v-if="this.training">训练模式</h3>
                <div class="asider" v-show="this.training">
                    <el-select v-model="selName" filterable placeholder="请选择股票">
                        <el-option v-for="item in nameList" :key="item.code" :label="item.name" :value="item.code"
                            @change="this.codeName = item.name" />
                    </el-select>
                    <br />
                    <el-checkbox class='' v-model="checked1" label="随机提取数据" size="small" />
                    <el-date-picker class='' v-model="nextTime" type="date" placeholder="Pick a day" />
                    <el-button class="ml-4" v-if="this.checked1" @click="randomDate(selName)">随机选择日期</el-button>
                    <el-button v-else @click="getDetail(selName, nextTime)">确定</el-button><br />
                    <br />
                    <span class="font-text" style="color:red;">{{ codeName }}
                        <span v-show="this.nextTime">{{ getShowDate(nextTime) }}</span>
                        {{ closeMoney }}
                    </span>
                    <div v-if="this.recordData">
                        <span>初始资金<el-input type="small" v-model="asset0" style="width:80px; " /></span>
                        <span>手续费<el-input type="small" v-model="fees0" style="width:45px; " />%</span>
                    </div>
                    <el-divider />
                    <el-button @click="startTrain">下一K线</el-button>
                    <el-button @click="reStart">重新训练</el-button>
                    <el-button @click="this.training = false">关闭训练</el-button>
                    <br />
                    <el-button type="danger" @click="buy">买入</el-button>
                    <el-dialog v-model="tobuy" title="买入" width="25%">
                        <el-form :model="formData" ref="record" label-position="right" class="to-record">
                            <el-form-item prop="money">
                                买入价格：<el-input v-model="formData.money" />元
                            </el-form-item>
                            <el-form-item prop="trades">
                                可买数量：{{ formData.trades }}股
                            </el-form-item>
                            <el-form-item prop="volume">
                                买入数量：<el-input v-model="formData.volume" @input="toupdate(formData.volume)" />股
                            </el-form-item>
                            <el-form-item prop="asset">
                                可用资金：{{ formData.asset }}元
                            </el-form-item>
                            <el-form-item prop="volume">
                                买入资金：<el-input v-model="formData.turnover" @input="toupdate1(formData.turnover)" />元
                            </el-form-item>
                            <el-button @click="buyNumber(1)">全量</el-button>
                            <el-button @click="buyNumber(2)">1/2</el-button>
                            <el-button @click="buyNumber(3)">1/3</el-button>
                            <el-button @click="buyNumber(6)">1/6</el-button>
                            <el-button type="danger" plain @click="getBuy(formData)">买入</el-button>
                            <el-button type="denger" plain @click="this.tobuy = false">关闭</el-button>
                        </el-form>
                    </el-dialog>

                    <el-button type="danger" @click="sell">卖出</el-button>
                    <el-dialog v-model="tosell" title="买出" width="25%">
                        <el-form :model="formData" ref="record" label-position="right">
                            <el-form-item prop="money">卖出价格：<el-input v-model="formData.money" />元</el-form-item>
                            <el-form-item>可卖数量：{{ formData.volumes }}股</el-form-item>
                            <el-form-item prop="volumes">
                                卖出数量：<el-input v-model="formData.volume" @input="toupdate(formData.volume)" />股
                            </el-form-item>
                            <el-form-item>可用资金：{{ balance }}元</el-form-item>
                            <el-form-item props="turnover">
                                卖出资金：<el-input v-model="formData.turnover"
                                    @input="toupdate1(formData.turnover)"></el-input>元
                            </el-form-item>
                            <el-button @click="sellNumber(1)">全量</el-button>
                            <el-button @click="sellNumber(2)">1/2</el-button>
                            <el-button @click="sellNumber(3)">1/3</el-button>
                            <el-button @click="sellNumber(6)">1/6</el-button>
                            <el-button type="danger" plain @click="getSell(formData)">买出</el-button>
                            <el-button type="denger" plain @click="this.tosell = false">关闭</el-button>
                        </el-form>
                    </el-dialog>

                    <el-divider />
                    <div class="current-money">
                        当前资产：{{ currentMoney }}
                        资产余额：{{ balance }}
                        <div style="margin: 10px 0px;">
                            多头市值：{{ codeMoney }}
                            空头市值：0.00
                        </div>
                    </div>
                </div>
            </el-aside>
            <el-main>
                <div id='myChart' ref="myChart" style="width:100%; height:500px"></div>
            </el-main>
        </el-container>
        <el-container>
            <router-view></router-view>
        </el-container>
    </div>
</template>

<script>
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import transaction from './transaction.vue'
export default {
    name: "codeDetail",
    components: {
        transaction
    },
    data() {
        return {
            tobuy: false,
            tosell: false,
            training: false,
            checked1: false,
            myChart: "", //
            selName: "", //股票代码
            codeName: "", //股票名称
            closeMoney: '',//股票收盘价
            nextTime: "", //股票日期、所选时间
            tradesNum: '', //股票数量
            nameList: {},
            detailChart: [], //所选时间到最新时间所有数据
            option: {}, //echarts
            data0: "",
            asset0: 1000000,
            fees0: 0.1,
            detailData: [],
            currentMoney: '', //当前资产
            balance: '', //资金余额
            codeMoney: 0.00, //多头市值
            recordData: {},
            formData: { //交易记录
                date: '',
                sale: '',
                money: 0.00, //成交价
                volume: 0, //成交量
                volumes: 0, //卖出的量
                turnover: 0,//成交额
                premium: undefined, //手续费
                profit: undefined, // 盈亏
                ratio: undefined, //盈亏率
                name: '',
                code: '',
                trades: 0,//总量
                asset: 0, //总额
                fees: 0//手续费 %
            }
        }
    },
    mounted() {
        this.getCodeName()
        this.$router.push('/')
        this.currentMoney = this.asset0
        this.balance = this.currentMoney
        console.log("vuex",this.$store.state.recordData);
    },

    methods: {
        buy() {
            this.tobuy = true
            this.formData = {
                name: this.codeName,
                code: this.selName,
                date: this.nextTime,
                sale: '买入',
                money: this.closeMoney,
                asset: this.currentMoney,
                fees: this.fees0,
                trades: this.tradesNum
            }
            console.log("当前金额", this.formData.asset);
        },

        sell() {
            this.tosell = true
            this.formData = {
                name: this.codeName,
                code: this.selName,
                date: this.nextTime,
                sale: '卖出',
                money: this.closeMoney,
                asset: this.balance,
                fees: this.fees0,
                volumes: this.$store.state.recordData[0].volume,
                volume: this.$store.state.recordData[0].volume,
                turnover: this.closeMoney * this.recordData.volume
            }

        },

        getBuy(item) {
            this.balance = item.asset - item.money * item.volume
            item.turnover = Math.round(item.money * item.volume * 100) / 100
            this.recordData = item
            this.codeMoney = Math.round(this.closeMoney * this.recordData.volume * 100) / 100
            this.currentMoney = this.balance + this.codeMoney
            console.log("记录：", item);
            this.$store.commit('add', this.recordData)
            console.log("buy", this.$store.state.recordData);
            this.tobuy = false
        },

        getSell(item) {
            console.log("volume", this.$store.state.recordData[0].volume, item.volume);
            //手续费 = 成交价*成交量*fees
            item.premium = item.money * item.volume * item.fees * 0.01
            item.turnover = item.volume * item.money
            this.balance = this.balance + item.volume * item.money - item.premium
            // 盈亏 = (现成交价 - 前成交价)* 现成交量 - 手续费
            item.profit = (item.money - this.$store.state.recordData[0].money) * item.volume - item.premium
            // 盈亏率 = 盈亏 / 前成交价 * 现成交量
            item.ratio = Math.round((item.profit / (this.$store.state.recordData[0].money * item.volume)) * 10000) / 100
            console.log("手续费", item.premium, "盈亏", item.profit, "盈亏率", item.ratio);
            
            this.recordData = item
            // 剩余成交量 = 前成交量 - 现成交量 
            this.recordData.volume = this.$store.state.recordData[0].volume - item.volume
            this.codeMoney = this.closeMoney * (this.$store.state.recordData[0].volume - item.volume)

            this.currentMoney = this.balance + this.codeMoney

            this.$store.commit('add', this.recordData)
            console.log("sell", this.$store.state.recordData);

            console.log("股票数量：", this.recordData.volume, item.volume);
            this.tosell = false

        },

        buyNumber(a) {
                this.formData.volume = Math.floor(this.formData.trades / a)
                this.toupdate(this.formData.volume)
        },

        sellNumber(a) {
            if (this.time) {
                clearTimeout(this.time)
            }
            this.time = setTimeout(() => {
                this.formData.volume = Math.floor(this.formData.volumes / a)
                this.toupdate(this.formData.volume)
            }, 1000)
        },

        toupdate(num) {
            this.formData.turnover = this.formData.money * num
            if (this.formData.turnover > this.formData.asset) {
                this.formData.volume = Math.floor(this.formData.asset / this.formData.money)
                this.formData.turnover = this.formData.money * this.formData.volume
            }
        },

        toupdate1(num) {
            if (num > this.formData.asset) {
                num = this.formData.asset
                this.formData.volume = Math.floor(num / this.formData.money)
                this.formData.turnover = this.formData.money * this.formData.volume
            }
            this.formData.volume = num / this.formData.money

        },
        // 得到所有的股票代码和名称
        getCodeName() {
            this.$axios({
                method: "GET",
                url: "/api/selectAll",
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                },
            }).then(res => {
                console.log("股票代码", res);
                this.nameList = res.data
            })
        },
        
        startTrain() {
            if (this.detailData.length < this.detailChart.length) {
                this.detailData.push(this.detailChart[this.detailData.length])
                this.detailData.shift()
                this.detailChart.shift()
                this.nextTime = this.detailChart[this.detailData.length - 1].date
                this.codeName = this.detailChart[this.detailData.length - 1].name
                this.closeMoney = this.detailChart[this.detailData.length - 1].close
                console.log("1", this.formData.volume, "2", this.recordData.volume);
                this.codeMoney = this.closeMoney * this.formData.volume
                this.currentMoney = this.balance + this.codeMoney

                this.myChart = echarts.init(document.getElementById("myChart"))
                console.log("hahahaha", this.formatDate(this.nextTime));
                this.data0 = this.setCodeData(this.detailData)
                this.option = {
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'cross'
                        }
                    },
                    xAxis: {
                        data: this.data0.categoryData
                    },
                    yAxis: {
                        scale: true,
                        splitArea: {
                            show: true
                        }
                    },
                    series: [
                        {
                            type: 'candlestick',
                            data: this.data0.values
                        }
                    ]
                };
                this.myChart.setOption(this.option)
            } else {
                ElMessage({
                    message: '已是最新数据',
                    type: 'error',
                    icon: 'Bell'
                })
            }
        },
        // 划分所有的数据
        setCodeData(data) {
            let categoryData = []
            let values = []
            let trades = []
            let transactions = []
            data.forEach(item => {
                categoryData.push(this.getShowDate(item.date));
                values.push([item.open, item.close, item.lowest, item.highest])
                trades.push(item.traded)
                transactions.push(item.transaction)
            })
            return {
                categoryData: categoryData, //日期
                values: values, // 
                trades: trades, //交易量
                transactions: transactions //交易额
            }
        },
        // x轴显示的时间格式
        getShowDate(dateday) {
            let getTime = new Date(dateday)
            return getTime.getFullYear() + "/" + (getTime.getMonth() + 1) + "/" + getTime.getDate();
        },
        // 发送给后端的时间格式
        formatDate(currentTime) {
            let formatTime = new Date(currentTime)
            return formatTime.getFullYear() + "-"
                + ((formatTime.getMonth() + 1) < 10 ? "0" + (formatTime.getMonth() + 1) : (formatTime.getMonth() + 1)) + "-"
                + (formatTime.getDate() < 10 ? "0" + formatTime.getDate() : formatTime.getDate()) + " "
                + "00:00:00";
        },
        // 获取随机时间并显示echarts
        randomDate(a) {
            let num1 = ''
            this.$axios({
                method: 'GET',
                url: '/api/selectOne/' + a,
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                },
            }).then(res => {
                num1 = res.data[0].date
                const moment = require('moment')
                const momentRandom = require('moment-random');
                moment().format()
                var randomdate = momentRandom('2022/12/6', num1)
                var datestr = moment(randomdate).format("YYYY-MM-DD");
                console.log("所选时间", datestr);
                this.nextTime = new Date(datestr)
                this.getDetail(this.selName, this.nextTime)
            })
        },
        //  数据显示
        getDetail(a, b) {
            this.option = {}
            this.detailChart = []
            this.detailData = []
            if (this.time) {
                clearTimeout(this.time)
            }
            this.time = setTimeout(() => {
                this.$axios({
                    method: "GET",
                    url: "/api/selectTime?code=" + a + "&date=" + this.formatDate(b),
                    headers: {
                        'Content-Type': 'application/json;charset=UTF-8',
                    },
                }).then(res => {
                    if (res.data != null) {
                        console.log(res.data);
                        this.myChart = echarts.init(document.getElementById("myChart"))
                        this.detailChart = res.data
                        for (let i = 0; res.data[i].date < this.formatDate(b); i++) {
                            this.detailData.push(res.data[i])
                        }
                        this.nextTime = this.detailChart[this.detailData.length].date
                        this.codeName = this.detailChart[this.detailData.length].name
                        this.closeMoney = this.detailChart[this.detailData.length].close
                        this.tradesNum = this.detailChart[this.detailData.length].traded
                        this.data0 = this.setCodeData(this.detailData)
                        console.log("data0", this.data0);
                        this.option = {
                            tooltip: {
                                trigger: 'axis',
                                axisPointer: {
                                    type: 'cross'
                                }
                            },
                            xAxis: {
                                data: this.data0.categoryData
                            },
                            yAxis: {
                                scale: true,
                                splitArea: {
                                    show: true
                                }
                            },
                            series: [
                                {
                                    type: 'candlestick',
                                    data: this.data0.values
                                }
                            ]
                        };
                        this.myChart.setOption(this.option)
                    }
                })
            }, 1000)

        },
        reStart() {
            this.$confirm('确认清除记录重新开始吗?', '提示', {
            }).then(() => {
                this.recordData = []
                this.$store.commit('del', this.$store.state.recordData)
                this.$router.push('/')
            }).catch(() => {
            })
        },

    },
}
</script>

<style scoped>
.start-stock {
    font-size: xx-large;
    padding: 30px 50px;
    margin: 10%;
}

.asider {
    width: 90%;
    margin: 0 auto;
    box-sizing: border-box;
    box-shadow: 0px 1px 10px rgba(0.5, 0, 0, 0.1);
    border-radius: 15px;
    padding: 20px 10px;
}

.current-money {
    border: 1px solid gainsboro;
    padding: 10px;
}

.el-input {
    padding: 2px;
    width: 100px;
}

.col-stock {
    margin-top: 20px;
}

.font-text {
    font-size: smaller;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    width: 400px;
}
</style>